<template>
  <!-- vue动画
        条件：进入、离开动作
         单元素动画
             1：用transition包住
             2:在transition加入name属性
                name的值是后面css的前缀
                .xxx-enter-active:进入过程中一直存在的class,常用于承载transition,animation
                .xxx-enter:进入过程中希望从什么状态变到正常状态
                .xxx-leave-active:离开过程中一直存在的class,常用于承载transition,animation
                .xxx-leave-to:离开过程中希望从正常状态变到什么状态
         多元素动画
            用transition-group包住
            每一个动画元素都要加key
 -->

  <div class="upload-img">
    <el-upload
      class="avatar-uploader"
      action="#"
      :show-file-list="false"
      :before-upload="beforeAvatarUpload"
      :http-request="httpRequest"
    >
      <img v-if="value" v-imgerror :src="value" class="avatar">
      <i v-else class="el-icon-plus avatar-uploader-icon" />
    </el-upload>
    <!-- 删除 -->
    <i v-if="value" class="el-icon-delete del" @click="delClick" />
    <!-- 预览 -->
    <i v-if="value" class="el-icon-zoom-in big" @click="show = true" />
    <el-dialog title="图片预览" :visible.sync="show">
      <img class="img" :src="value" alt="">
    </el-dialog>
    <!-- 进度条 -->
    <transition name="xxx">
      <el-progress
        v-if="showProgress"
        :format="format"
        :width="178"
        class="progress"
        type="circle"
        :percentage="percentage"
      />
    </transition>
  </div>
</template>
<script>
import COS from 'cos-js-sdk-v5'
// 实例化（身份验证）
var cos = new COS({
  SecretId: 'AKIDNXR8bpeSF1JL8EyZopxRfdHgqGUeuEn8',
  SecretKey: 'HJ9mAbQEn7jgjY9swEI6yAamk7MN8hty'
})
export default {
  name: 'UploadImg',
  props: {
    value: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      show: false,
      showProgress: false,
      percentage: 0
    }
  },
  methods: {
    format(percentage) {
      return '百分比:' + percentage
    },
    beforeAvatarUpload(file) {
      const isJPG = file.type === 'image/jpeg' || file.type === 'image/png'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('上传头像图片只能是 JPG,PNG 格式!')
      }
      if (!isLt2M) {
        this.$message.error('上传头像图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    httpRequest(res) {
      const file = res.file
      this.showProgress = true
      cos.uploadFile(
        {
          Bucket: 'abc-1305249343' /* 填写自己的 bucket，必须字段 */,
          Region: 'ap-chongqing' /* 存储桶所在地域，必须字段 */,
          Key:
            '93/' +
            file.name /* 存储在桶里的对象键（例如:1.jpg，a/b/test.txt，图片.jpg）支持中文，必须字段 */,
          Body: file, // 上传文件对象
          SliceSize:
            1024 *
            1024 *
            0.5 /* 触发分块上传的阈值，超过5MB使用分块上传，小于5MB使用简单上传。可自行设置，非必须 */,
          onProgress: (progressData) => {
            this.percentage = +(progressData.percent * 100).toFixed(2)
            if (progressData.percent === 1) {
              setTimeout(() => {
                // this.showProgress = false
              }, 1000)
            }
            // console.log(JSON.stringify(progressData))
          }
        },
        (err, data) => {
          if (err) {
            console.log('上传失败', err)
          } else {
            this.$emit('input', 'http://' + data.Location)
            console.log('上传成功', data)
          }
        }
      )
    },
    delClick() {
      this.$emit('input', '')
    }
  }
}
</script>
<style lang="scss" scoped>
.avatar-uploader ::v-deep .el-upload {
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
}
.avatar-uploader ::v-deep .el-upload:hover {
  border-color: #409eff;
}
.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  line-height: 178px;
  text-align: center;
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
}
.upload-img {
  position: relative;
  width: 178px;
  &:hover {
    .del,
    .big {
      display: block;
    }
  }
  .del,
  .big {
    cursor: pointer;
    position: absolute;
    display: none;
    right: 10px;
    top: 5px;
    font-size: 20px;
  }
  .big {
    right: 40px;
  }
  .img {
    width: 100%;
  }
}
.progress {
  position: absolute;
  left: 0;
  top: 0;
  background-color: #fff;
}
.xxx-enter-active,
.xxx-leave-active {
  transition: all 0.5s;
}
.xxx-enter,
.xxx-leave-to {
  opacity: 0;
}
</style>
